package com.tanhua.server.service;

import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.commons.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.server.Interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class SoundService {

    @Reference
    private SoundApi soundApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired(required = false)
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Reference
    private UserInfoApi userInfoApi;

    private static final String tanhuaSound = "tanhua_sound_";

    /**
     * 接口名称：桃花传音-发送语音（学生实战）
     * @param soundFile
     * @return
     */
    public ResponseEntity<Object> updateVideo(MultipartFile soundFile) throws IOException {
        //1.得到用户id
        Long userId = UserHolder.getUserId();

        //2.存入oss
        //2.1得到上传音频的地址
        String soundFilename = soundFile.getOriginalFilename();

        //2.3得到上传文件的地址
        String soundUrl = ossTemplate.upload(soundFilename, soundFile.getInputStream());

        //3.存入mongoDB
        Sound sound = new Sound();
        sound.setId(ObjectId.get());
        sound.setUserId(userId);
        sound.setSoundUrl(soundUrl);
        //默认设置为0   --0.为未审核  --1.为审核通过  --2.为审核不通过
        sound.setState(0);

        //保存
        soundApi.save(sound);

        //4.发送tanhua_video主键id给rocketMQ消息中间件进行审核
        Map<String, String> map = new HashMap<>();
        map.put("id", sound.getId().toString());
        map.put("soundUrl", sound.getSoundUrl());

        rocketMQTemplate.convertAndSend("tanhua-sound", JSON.toJSONString(map));

        return ResponseEntity.ok(null);
    }

    public ResponseEntity<Object> receiveVideo() {
        //1. 获得本用户的id,根据本用户的id去redis中查询该用户的剩余次数
        Long userId = UserHolder.getUserId();
        String key = tanhuaSound + userId.toString();
        Integer count = null;


        //2. 判断key存不存在
        //2.1 key存在且值大于0 , 则count -1
        if(redisTemplate.hasKey(key)) {
            count = Integer.valueOf(redisTemplate.opsForValue().get(key));
            if(count > 0){

                count = Integer.valueOf(redisTemplate.opsForValue().get(key));
                count--;
                redisTemplate.opsForValue().set(key, String.valueOf(count));

            }else {
                count = 0;
                SoundVo soundVo = new SoundVo();
                soundVo.setRemainingTimes(0);
                //3.1 获得传音的用户的详细信息userInfo
                UserInfo userInfo = userInfoApi.findById(userId);
                BeanUtils.copyProperties(userInfo,soundVo);
                return ResponseEntity.ok(soundVo);
            }

            //2.2 key不存在，则count设置为10
        }else {
            redisTemplate.opsForValue().set(key, String.valueOf(9));
            count = 9;
        }
        //2. 查询该用户没有听过的语音
        Sound sound = soundApi.findOneSound(userId);

        //3. 封装数据
        SoundVo vo = new SoundVo();

        Long videoUserId = sound.getUserId();
        //3.1 获得传音的用户的详细信息userInfo
        UserInfo userInfo = userInfoApi.findById(videoUserId);
        BeanUtils.copyProperties(userInfo,vo);

        vo.setSoundUrl(sound.getSoundUrl());
        vo.setRemainingTimes(count);

        return ResponseEntity.ok(vo);
    }
}
